package wxpay

import (
	"crypto"
	cr "crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

// ------------payUtil(支付工具) - 支付通过模块 -----------------//

const (
	PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
	PEM_END = "\n-----END RSA PRIVATE KEY-----"
)

var (
	BeijingLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
)

// 随机字符串
func RandomString(n int) string {
	var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

	b := make([]rune, n)
	length := len(letter)

	for i := range b {
		b[i] = letter[rand.Intn(length)]
	}

	return string(b)
}

// 随机32位字符串
func NonceStr() string {
	return RandomString(32)
}

// FormatTime time.Time => "yyyyMMddHHmmss."
func FormatTime(t time.Time) string {
	return t.In(BeijingLocation).Format("20060102150405")
}

// ParseTime "yyyyMMddHHmmss" => time.Time.
func ParseTime(value string) (time.Time, error) {
	return time.ParseInLocation("20060102150405", value, BeijingLocation)
}

func TimeStamp() string  {
	return strconv.FormatInt(time.Now().Unix(), 10)
}

func SpliceString(s string) string {
	return fmt.Sprintf(`"%s"`, s)
}

func RsaSign(signContent string, privateKey string, hash crypto.Hash) string {
	shaNew := hash.New()
	shaNew.Write([]byte(signContent))
	hashed := shaNew.Sum(nil)
	priKey, err := ParsePrivateKey(privateKey)
	if err != nil {
		panic(err)
	}

	signature, err := rsa.SignPKCS1v15(cr.Reader, priKey, hash, hashed)
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(signature)
}

func ParsePrivateKey(privateKey string)(*rsa.PrivateKey, error) {
	privateKey = FormatPrivateKey(privateKey)
	// 2、解码私钥字节，生成加密对象
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("私钥信息错误！")
	}
	// 3、解析DER编码的私钥，生成私钥对象
	priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return priKey, nil
}

func FormatPrivateKey(privateKey string) string  {
	if !strings.HasPrefix(privateKey, PEM_BEGIN) {
		privateKey = PEM_BEGIN + privateKey
	}
	if !strings.HasSuffix(privateKey, PEM_END) {
		privateKey = privateKey + PEM_END
	}
	return privateKey
}

